package com.my.simple.web.controller.admin;

import com.my.simple.common.enums.SecurityEnum;
import com.my.simple.common.util.EHCacheUtils;
import com.my.simple.entity.auth.User;
import com.my.simple.service.auth.AuthService;
import com.my.simple.service.auth.UserService;
import com.my.simple.web.vo.LoginVO;
import com.my.simple.web.vo.RegisterVO;
import com.my.simple.web.vo.ResponseData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;

@RestController
@RequestMapping(value = "login")
public class LoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private AuthService authService;

    @PostMapping(value = "/signin")
    public ResponseEntity<ResponseData> signIn(@Valid LoginVO loginItem) {
        ResponseData responseData = new ResponseData();
        String userAccount = loginItem.getUserAccount();
        String password = loginItem.getPassword();
        User user = userService.getUserByAccount(userAccount.trim());

        if (user == null) {
            throw new IllegalArgumentException("用户名或密码不正确");
        } else {
            if (!password.equals(user.getPassword())) {
                throw new IllegalArgumentException("用户名或密码不正确");
            }
        }

        //create token and save token user mapping info
        String token = authService.signToken(user.getUserId());
        //add token to response http header
        HttpHeaders headers = new HttpHeaders();
        headers.add(SecurityEnum.MyToken.name(), token);

        ResponseEntity<ResponseData> responseEntity = new ResponseEntity<ResponseData>(responseData, headers, HttpStatus.OK);
        return responseEntity;
    }

    @PostMapping(value = "register")
    public ResponseEntity<ResponseData> register(@RequestBody RegisterVO registerInfo) {
        ResponseData responseData = new ResponseData();
        User userItem = new User();
        //register
        userItem.setUserAccount(registerInfo.getUserAccount());
        userItem.setUserName(registerInfo.getUserName());
        userItem.setEmail(registerInfo.getEmail());
        userItem.setPassword(registerInfo.getPassword());
        userItem.setBirthday(registerInfo.getBirthday());
        userItem.setAddress(registerInfo.getAddress());
        userItem.setMobile(registerInfo.getMobile());
        userItem.setActive(true);
        userItem.setUpdateDate(new Date());
        userService.addUser(userItem);
        LOGGER.info("add user id is {}", userItem.getUserId());

        //login by create token and save token user mapping info
        String token = authService.signToken(userItem.getUserId());
        //add token
        //add token to response http header
        HttpHeaders headers = new HttpHeaders();
        headers.add(SecurityEnum.MyToken.name(), token);

        responseData.setMessage("register successful");
        ResponseEntity<ResponseData> responseEntity = new ResponseEntity<ResponseData>(responseData, headers, HttpStatus.OK);
        return responseEntity;
    }

    @PostMapping(value = "logout")
    public ResponseEntity<ResponseData> logout(HttpServletRequest request) {
        ResponseData responseData = new ResponseData();
        String token = request.getHeader(SecurityEnum.MyToken.name());

        if (StringUtils.isNotBlank(token)) {
            Object obj = EHCacheUtils.get(token);
            if (obj != null) {
                EHCacheUtils.remove(token);
            } else {
                throw new IllegalArgumentException("用户未登陆");
            }
        } else {
            throw new IllegalArgumentException("用户未登陆");
        }

        responseData.setMessage("logout successful");
        ResponseEntity<ResponseData> responseEntity = new ResponseEntity<ResponseData>(responseData, HttpStatus.OK);
        return responseEntity;
    }
}
